package com.wosai.teach.listener;

import java.io.File;
import java.util.Date;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.HttpHandler.State;
import com.wosai.teach.adapter.SimulationAdapter.ViewHolder;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.CheckSureDialog;
import com.wosai.teach.entity.DownloadInfo;
import com.wosai.teach.entity.ExpDateRel;
import com.wosai.teach.entity.Experiment;
import com.wosai.teach.entity.GridInfo;
import com.wosai.teach.entity.User;
import com.wosai.teach.fragment.AppFragment;
import com.wosai.teach.service.DownLoadFactory;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.DBControl;
import com.wosai.teach.utils.NetWorkUtils;
import com.wosai.teach.utils.OtherUtils;
import com.wosai.teach.utils.SynchUtils;

/**
 * @author qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015年9月1日 上午10:19:05
 * @desc : 实验点击逻辑
 */
public class SimuOnItemClickListener implements OnItemClickListener {

	private DBControl db;
	private AppFragment fragment;
	private Activity activity;
	private DownLoadFactory factory;

	public SimuOnItemClickListener(Activity activity, DBControl db,
			DownLoadFactory factory, AppFragment fragment) {
		this.db = db;
		this.factory = factory;
		this.fragment = fragment;
		this.activity = activity;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (SynchUtils.isFastClick(view.hashCode())) {
			return;
		}
		GridInfo grid = (GridInfo) parent.getAdapter().getItem(position);
		Experiment exp = db.findFirst(Selector.from(Experiment.class).where(
				"expId", "=", grid.getRelId()));
		PackageInfo pi = AppUtil.getPackageInfo(exp.getApkPackageName());
		int ver = AppUtil.getVersionCode(pi);
		if (ver > 0 && exp.getApkVer() > ver) {
			// 更新
			ViewHolder vh = (ViewHolder) view.getTag();
			downloadApk(exp, vh, true);
		} else if (ver > 0) {
			// 打开apk
			openSoft(exp);
		} else {
			// 下载
			ViewHolder vh = (ViewHolder) view.getTag();
			downloadApk(exp, vh, false);
		}
	}

	/**
	 * 暂停下载
	 * 
	 * @param expId
	 */
	public void stopDownload(String expId) {
		factory.stopDownload(expId);
	}

	public void downloadApk(final Experiment exp, final ViewHolder vh,
			boolean upadte) {
		final DownloadInfo downloadInfo = refreshDownLoadInfo(exp);
		HttpHandler.State state = downloadInfo.getState();
		String text = "";
		String key = "";
		if (upadte) {
			key = "更新";
		} else {
			key = "下载";
		}
		switch (state) {
		case STARTED:
		case LOADING:
			factory.stopDownload(exp.getExpId() + "");
			vh.showPause(downloadInfo.getPercent());
			break;
		case WAITING:
		case CANCELLED:
		case FAILURE:
			if (state == State.FAILURE || state == State.CANCELLED) {
				text = "该实验未" + key + "完成，是否继续下载";
			} else {
				text = "该实验未" + key + "，是否下载";
			}
			CheckSureDialog dialog = new CheckSureDialog(activity);
			dialog.init(new CheckSureListener() {
				@Override
				public void onOk() {
					checkNetWork(downloadInfo.getState(), downloadInfo, exp, vh);
				}
			}, "提示", text);
			dialog.show();
			break;
		case SUCCESS:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			String savePath = downloadInfo.getFileSavePath();// apk路径
			if (OtherUtils.CheckNull(savePath)) {
				return;
			}
			intent.setDataAndType(Uri.fromFile(new File(savePath)),
					"application/vnd.android.package-archive");
			fragment.startActivityForResult(intent, C.REQUEST_CODE_INSTALL);
			factory.removeDownload2(downloadInfo);
			break;
		default:
			break;
		}

	}

	/**
	 * 根据网络类型操作
	 * 
	 * @param state
	 *            状态
	 * @param downloadInfo
	 * @param exp
	 * @param vh
	 *            视图
	 */
	public void checkNetWork(final State state,
			final DownloadInfo downloadInfo, final Experiment exp,
			final ViewHolder vh) {
		int netType = NetWorkUtils.getNetworkType(activity);
		if (netType == NetWorkUtils.NETTYPE_NO) {
			fragment.toastShow("亲，请连接网络先");
			return;
		}
		if (netType != NetWorkUtils.NETTYPE_WIFI) {
			CheckSureDialog dialog = new CheckSureDialog(activity);
			dialog.init(new CheckSureListener() {
				@Override
				public void onOk() {
					startDownload(state, downloadInfo, exp, vh);
				}
			}, "提示", "您当前未连接WIFI，是否确认下载安装");
			dialog.show();
		} else {
			startDownload(state, downloadInfo, exp, vh);
		}
	}

	/**
	 * 开始下载
	 */
	private void startDownload(State state, DownloadInfo downloadInfo,
			Experiment exp, ViewHolder vh) {
		DownloadRequestCallBack callBack = new DownloadRequestCallBack(vh,
				downloadInfo, fragment, factory, this, exp);
		if (state == State.WAITING) {
			factory.addNewDownload(downloadInfo, callBack);
		} else if (state == State.CANCELLED || state == State.FAILURE) {
			factory.resumeDownload(exp.getExpId() + "", callBack);
		}
	}

	/**
	 * 刷新获取downloadInfo
	 * 
	 * @param exp
	 * @return
	 */
	public DownloadInfo refreshDownLoadInfo(Experiment exp) {
		DownloadInfo downloadInfo = factory
				.getDownloadInfo(exp.getExpId() + "");
		String tt[] = exp.getApkURL().split("/");
		String fileName = tt[tt.length - 1];
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File tmpFile = new File(sdcard + "/teach_platform");
		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		String savePath = sdcard + "/teach_platform/" + fileName;
		if (downloadInfo == null) {
			downloadInfo = new DownloadInfo();
			downloadInfo.setDownloadUrl(exp.getApkURL());
			downloadInfo.setAutoRename(false);
			downloadInfo.setAutoResume(true);
			downloadInfo.setFileName(fileName);
			downloadInfo.setFileSavePath(savePath);
			downloadInfo.setRelId(exp.getExpId() + "");
			downloadInfo.setState(State.WAITING);
		}
		File apk = new File(savePath);
		if (apk.exists() && apk.isFile()) {
			if (downloadInfo.getState() == State.FAILURE) {
				// 下载失败.删除后,再重新下载
				delApk(exp);
			} else if (downloadInfo.getState() == State.WAITING) {
				downloadInfo.setState(State.SUCCESS);
			}
		} else {
			if (downloadInfo.getState() == State.SUCCESS) {
				// 下载成功,但是没有文件,文件被删除,重新下载
				downloadInfo.setState(State.WAITING);
			}
		}
		return downloadInfo;
	}

	/**
	 * 删除apk包
	 * 
	 * @param exp
	 */
	private void delApk(Experiment exp) {
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File tmpFile = new File(sdcard + "/teach_platform");
		if (!tmpFile.exists()) {
			return;
		}
		String tt[] = exp.getApkURL().split("/");
		String fileName = tt[tt.length - 1];
		String savePath = sdcard + "/teach_platform/" + fileName;
		File apk = new File(savePath);
		if (apk.exists() && apk.isFile()) {
			apk.delete();
		}
	}

	/**
	 * 打开软件
	 */
	public void openSoft(Experiment exp) {
		// boolean toLogin = AppUtil.toLogin(this);
		if (!SynchUtils.canOpen()) {
			return;
		}
//		Log.e("openSoft:" + exp.getExpName(), "打开");
		refreshDateRel(exp);
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		ComponentName cn = new ComponentName(exp.getApkPackageName(),
				exp.getApkClassName());
		intent.setComponent(cn);
		User user = db.findFirst(User.class);
		intent.putExtra("userId", user.getUserId());
		fragment.startActivityForResult(intent, C.REQUEST_CODE_OPEN_SOFT);
	}

	/**
	 * 刷新打开记录
	 */
	public void refreshDateRel(Experiment exp) {
		ExpDateRel rel = db.findFirst(Selector.from(ExpDateRel.class).where(
				"expId", "=", exp.getExpId()));
		if (rel == null) {
			rel = new ExpDateRel();
			rel.setCreateDate(new Date().getTime());
			rel.setExpId(exp.getExpId() + "");
		}
		rel.setUpdateDate(new Date().getTime());
		db.save(rel);
	}
}
